# Moths - an environment for mathy calculations
# Copyright (C) 2006 Mike Sutjipto
# Licensed under the GPL

module Moths
  
  # Essentially this represents a function call, but also
  # handles 'variables' (which are just functions without arguments)
  #
  class Identifier < Expression
    @id
    @args # an array of expressions

    attr_reader :id, :args

    def initialize(id, args)
      @id = id.to_sym
      @args = args
      @precedence = 7
    end

    def eval(env)
      defn = env.resolve(self)

      # create a new child environment for the function call
      # bind arguments to their identifiers in the environment
      childEnv = Environment.new(env)
      defn.arg_list.each_index do |i|
        childEnv.define(Definition.new(defn.arg_list[i], [], @args[i]))
      end

      return defn.expr.eval(childEnv)
    end

    def to_s
      return '(' + @id.to_s + ' ' + @args.join(' ') + ')'
    end

    # Adds an expression to be bound to one the functions arguments
    #
    def add_arg(arg)
      @args = @args << arg
    end

    # Returns the number of arguments
    #
    def arg_num
      return @args.length
    end
  end
  
end
